package com.slmxz.tms.common.util;

import com.slmxz.tms.common.constant.SecurityConstants;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Locale;

public class RequestUtil {
    private static final ThreadLocal<HttpServletRequest> threadLocal = new ThreadLocal<>();

    public static void shareRequest(HttpServletRequest request) {
        threadLocal.set(request);
    }

    public static HttpServletRequest getRequest() {
        HttpServletRequest request = threadLocal.get();
        if(request != null){
            return request;
        }
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            return null;
        }
        return requestAttributes.getRequest();
    }

    public static void remove() {
        threadLocal.remove();
    }

    /**
     * 从请求头中获取授权token
     */
    public static String getAuthToken(){
        HttpServletRequest request = getRequest();
        if(request == null){
            return null;
        }
        return request.getHeader(SecurityConstants.AUTHORIZATION_HEADER);
    }
    /**
     * 从请求头中获取授权token
     */
    public static String getLang(){
        String lang =  Locale.CHINA.toLanguageTag();;
        HttpServletRequest request = getRequest();
        if(request != null){
            lang = request.getHeader(SecurityConstants.ACCEPT_LANGUAGE);
            lang = lang.substring(0,lang.indexOf(","));
        }
        return lang;
    }

    public static String getBodyString(HttpServletRequest request) throws IOException {
        StringBuilder sb = new StringBuilder();
        InputStream inputStream = null;
        BufferedReader reader = null;
        try {
            inputStream = request.getInputStream();
            reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            String line = "";
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }
}
